#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <iostream>
#include <vector>
#include <sstream>
#include <algorithm>
#include <iterator>
#include <fstream>
using namespace std;

void error(const char *msg) {
	perror(msg);
	exit(0);
}

string get_file_name(string path) {
	string file_name = "";
	for (int var = path.length() - 1; var >= 0; --var) {
		if (path.at(var) == '/')
			break;
		file_name = path.at(var) + file_name;
	}
	return file_name;
}
int main(int argc, char *argv[]) {



	 int sock, n;
	   unsigned int length;
	   struct sockaddr_in server, from;
	   struct hostent *hp;
	   char buffer[256];

	string file_path;
	string request = "";
	ifstream myfile("client_files/index.txt");
	if (myfile.is_open()) {
		while (getline(myfile, file_path) && file_path.length() > 1) { //each requested file from server


			   if (argc != 3) { printf("Usage: server port\n");
			                    exit(1);
			   }
			   sock= socket(AF_INET, SOCK_DGRAM, 0);
			   if (sock < 0) error("socket");

			   server.sin_family = AF_INET;
			   hp = gethostbyname(argv[1]);
			   if (hp==0) error("Unknown host");

			   bcopy((char *)hp->h_addr,
			        (char *)&server.sin_addr,
			         hp->h_length);
			   server.sin_port = htons(atoi(argv[2]));
			   length=sizeof(struct sockaddr_in);
			   bzero(buffer,256);
			   request = "GET " + file_path + " HTTP/1.0";
			   n=sendto(sock,request.c_str(), strlen(request.c_str()),0,(const struct sockaddr *)&server,length);
			   if (n < 0) error("Sendto");
			   //cout <<"tmam0"<<endl;
			   n = recvfrom(sock,buffer,256,0,(struct sockaddr *)&from, &length);
			   if (n < 0) error("recvfrom");
			   //cout<<buffer<<endl;
			   //cout<<n<<endl;

			   recvfrom(sock,buffer,256,0,(struct sockaddr *)&server, &length);
			   cout<<buffer<<endl;//ok
			   sendto(sock,buffer, strlen(buffer),0,(const struct sockaddr *)&server,length);


			//write received file
			FILE * pFile;
			pFile = fopen(("client_files/" + get_file_name(file_path)).c_str(),
					"w");

			if (pFile != NULL) {
				//cout<<"not null"<<endl;
				while(n>0){ //write each chunk
					//cout<<"rec rec"<<endl;
					n= recvfrom(sock,buffer,256,0,(struct sockaddr *)&server, &length);//It stop here why?

				sendto(sock,buffer, strlen(buffer),0,(const struct sockaddr *)&server,length);
					//cout<<buffer<<endl;

					fwrite(buffer, sizeof(char), n, pFile);
					if(buffer == 0){
						break;
					}
				}
				close(sock);
				fclose(pFile);
			}

		}
		myfile.close();
	}
	return 0;
}
